package com.gxgeek.springweb.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gaoxing
 * @create 2018-08-30 下午1:38
 */
@Component
@Slf4j
public class SimpleFilter implements Filter{
    private static Map<Method,String> urlPatternMap = new ConcurrentHashMap<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        RequestMappingHandlerMapping requestMappingHandlerMapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
        for(Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()){
            urlPatternMap.put(entry.getValue().getMethod(),entry.getKey().getPatternsCondition().getPatterns().stream().findFirst().get());
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info(this.getClass().getSimpleName()+"  doFilter start ");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        String name = httpServletRequest.getHeader("name");
        if (!StringUtils.isEmpty(name)){
            log.info("从头中读取 name {}",name);
//            log.info("修改请求头 name为ab ");
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
